package com.starblink.brand.adapter

import android.annotation.SuppressLint
import android.graphics.*
import android.graphics.drawable.Drawable
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.Priority
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.CustomViewTarget
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import com.starblink.android.basic.adapter.BaseBindingVH
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.extension.businessSuffixId
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.util.ImageUtils
import com.starblink.basic.log.SKLogger
import com.starblink.basic.route.RoutePage
import com.starblink.basic.util.ActivityStackManage
import com.starblink.brand.R
import com.starblink.brand.bean.BrandMoreCardBean
import com.starblink.brand.databinding.ItemBrandMoreCardBinding
import kotlin.math.abs

class BrandMoreCardHolder (
    binding: ItemBrandMoreCardBinding,
): BaseBindingVH<BrandMoreCardBean, ItemBrandMoreCardBinding>(binding)  {
    //fgWidth正常应该减去2倍的边距
    // -2*ActivityStackManage.currentActivity().resources.getDimensionPixelSize(
    //     com.starblink.basic.style.R.dimen.d_20dp
    // )

    init {
        val layoutParams = StaggeredGridLayoutManager.LayoutParams(
            StaggeredGridLayoutManager.LayoutParams.MATCH_PARENT,
            ActivityStackManage.currentActivity().resources.getDimensionPixelSize(
                com.starblink.basic.style.R.dimen.d_138dp)
        ).apply {
            isFullSpan = true
        }
        itemView.layoutParams = layoutParams
    }

    var fgWidth =ActivityStackManage.currentActivity().resources.getDimensionPixelSize(
            com.starblink.basic.style.R.dimen.d_142dp
        )
    var fgHeight =ActivityStackManage.currentActivity().resources.getDimensionPixelSize(
        com.starblink.basic.style.R.dimen.d_128dp
    )
    var margin=ActivityStackManage.currentActivity().resources.getDimensionPixelSize(
        com.starblink.basic.style.R.dimen.d_1dp)

    override fun onBind(model: BrandMoreCardBean, position: Int) {
        val brandInfo=model.brandCollectionInfoVoF
        var bgResourceId =
            when (model.position%5) {
                0 -> {
                    R.drawable.bg_rect_jb_brand_1
                }
                1 -> {
                    R.drawable.bg_rect_jb_brand_2
                }
                2 -> {
                    R.drawable.bg_rect_jb_brand_3
                }
                3 -> {
                    R.drawable.bg_rect_jb_brand_4
                }
                else -> {
                    R.drawable.bg_rect_jb_brand_5
                }
            }
        val layoutParams = binding.ivProduct.layoutParams as RelativeLayout.LayoutParams
        var markResourceId =
            when (model.position%3) {
                0 -> {
                    binding.ivProductTag.visibleOrGone(false)
                    layoutParams.height=fgHeight
                    layoutParams.width=fgWidth
                    layoutParams.setMargins(0,0,0,0)//4个参数按顺序分别是左上右下
                    R.drawable.ic_brand_left_mix_1
                }
                1 -> {
                    binding.ivProductTag.visibleOrGone(true)
                    layoutParams.height=fgHeight-margin*2
                    layoutParams.width=fgWidth-margin
                    layoutParams.setMargins(0,0,margin,0)//4个参数按顺序分别是左上右下
                    R.drawable.ic_brand_left_mix_2_2
                }
                else -> {
                    binding.ivProductTag.visibleOrGone(false)
                    layoutParams.height=fgHeight-margin*2
                    layoutParams.width=fgWidth-margin
                    layoutParams.setMargins(0,0,margin,0)//4个参数按顺序分别是左上右下
                    R.drawable.ic_brand_left_mix_3
                }
            }
        binding.ivProduct.layoutParams=layoutParams

        binding.ivBrandLogo.load(brandInfo?.brandLogo, brandInfo?.brandName)
        binding.tvBrandName.text=brandInfo?.brandName
        brandInfo?.lowestDiscount?.let {
            binding.tvDiscountTag.text="${it.toFloat().toInt()}%"
        }
        binding.tvBrandProducts.text = "${if(brandInfo?.productNum?:0>1000) "1000+" else brandInfo?.productNum} Products"

        binding.viewBgItem.setImageResource(bgResourceId)
//        ImageUtils.loadImage(commContext(),brandInfo?.productImg,binding.ivProduct)

        //图片正交叠底
        if(model.newBitmap!=null){
            binding.ivProduct.setImageBitmap(model.newBitmap)
        }else {
            binding.ivProduct.visibleOrInVisible(false)
            binding.rlLayout.post {
                Glide.with(binding.ivProduct.context).asBitmap()
                    .apply(RequestOptions().apply {
                        format(DecodeFormat.PREFER_ARGB_8888)
                    })
                    .centerCrop()
                    .override(Target.SIZE_ORIGINAL).load(brandInfo?.productImg)
                    .skipMemoryCache(false)
                    .priority(Priority.IMMEDIATE)
                    .into(object : CustomViewTarget<ImageView, Bitmap>(binding.ivProduct) {
                        override fun onLoadFailed(errorDrawable: Drawable?) {
                            SKLogger.d("BrandMoreCardHolder", "onLoadFailed --- onLoadFailed --- ")
                        }

                        @SuppressLint("ResourceType")
                        override fun onResourceReady(
                            resource: Bitmap,
                            transition: Transition<in Bitmap>?
                        ) {
                            binding.ivProduct.setImageBitmap(resource)
                            var is3 = commContext().resources.openRawResource(markResourceId)
                            var maskSource = BitmapFactory.decodeStream(is3)
                            binding.ivProduct.toBitmap2LayoutEnhanced()?.let {
                                model.newBitmap =ImageUtils.maskBitmap(it,maskSource,fgWidth,fgHeight)
                                binding.ivProduct.visibleOrGone(true){
                                    setImageBitmap(model.newBitmap)
                                }
                            }
                        }

                        override fun onResourceCleared(placeholder: Drawable?) {
                        }

                    })
            }
        }



        itemView.trackData(
            page = SpmPageDef.BrandDetailPage,
            element = SpmElementDef.Element_33014,
            showRatio = 0.9f,
            params = mapOf("index" to "${model.position}","brandName" to (brandInfo?.brandName?:"")),
            businessSuffixID = businessSuffixId(model)
        )

        itemView.setOnClickListener {
            navigationTo(RoutePage.Brand.BRAND_COLLECTION){
                withString(RoutePage.Brand.ARG_brandName, brandInfo?.brandName)
                withString(RoutePage.Brand.ARG_brandCollectionId, brandInfo?.brandCollectionId)
                withString(RoutePage.Brand.ARG_productId, brandInfo?.productId)
            }
        }
    }

    /**
     * 处理bitmap的渐变色
     */
    fun getTransparentImage(sourceImg: Bitmap, position: Int): Bitmap? {
        var sourceImg = sourceImg
        try {
            val width = sourceImg.width
//        val height = sourceImg.height
            //        double radius = Math.sqrt(Math.pow(width / 2.0, 2) + Math.pow(height / 2.0, 2));//设置半径
            val endX = width / 3.0
            // 获得图片的ARGB值
            val argb =    IntArray(sourceImg.width * sourceImg.height)
            sourceImg.getPixels(
                argb, 0, sourceImg.width, 0, 0, sourceImg
                    .width, sourceImg.height
            )
            for (i in argb.indices) {
                val x = i % width
//            val y = i / width
                var startX = endX - x
                if (startX > 0 && startX < endX) {
                    //透明度
                    argb[i] =
                        (abs(endX - startX) / endX * 255).toInt() shl 24 or (argb[i] and 0x00FFFFFF)
                }
            }
            sourceImg = Bitmap.createBitmap(
                argb, sourceImg.width, sourceImg
                    .height, Bitmap.Config.ARGB_8888
            )
        } catch (e: Exception) {
            return null
        }
        return sourceImg
    }
}